package com.jun.admin.core.model.serializable;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.jun.admin.core.model.aspect.Desensitization;
import com.jun.admin.core.model.enums.DesensitizationEnum;

import java.io.IOException;
import java.util.Objects;

/**
 * @author yuejun.li
 * @date 2024/7/1 14:38:15
 * 自定义数据脱敏序列化
 */
public class DesensitizationJsonSerializable extends JsonSerializer<String> implements ContextualSerializer {

    private DesensitizationEnum desensitizationEnum;

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        //使用脱敏策略将字符串处理后序列化到json中
        jsonGenerator.writeString(desensitizationEnum.getDesensitization().apply(s));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        //获取属性上的Desensitization注解
        Desensitization annotation = beanProperty.getAnnotation(Desensitization.class);
        //注解不为空 && 属性类型必须是字符串类型
        if(Objects.nonNull(annotation) && Objects.equals(String.class,beanProperty.getType().getRawClass())){
            //设置脱敏策略
            this.desensitizationEnum = annotation.value();
            return this;
        }
        //返回默认的序列化器
        return serializerProvider.findValueSerializer(beanProperty.getType(),beanProperty);
    }
}
